package com.hp.bon.sgw.scsp;

import java.io.IOException;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ConcurrentHashMap;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.hp.bon.sgw.util.Comutils;

public class SCSPUtils {
	/**
	 * @param root
	 * @param fieldName
	 * @param isMandatory
	 * @return
	 * @throws FieldNotExistException
	 */
	public static String parseField(Element root, String fieldName,
			boolean isMandatory) throws FieldNotExistException {
		Attribute attrMID = root.attribute(fieldName);
		if(attrMID == null)
		{
			if(isMandatory)
			{
				throw new FieldNotExistException(fieldName);
			}
			else
			{
				return null;
			}
		}
		return attrMID.getStringValue();
	}
    public static void main(String[] args)  {
    	String str ="<CLR MID=\"CRM@001.ctnbc-bon.net;20100625140230003;87893\" SN=\"CRM@001.ctnbc-bon.net\" UID=\"name\" PWD=\"password\" />"; 
		Document doc;
		Element root = null;
		try {
			doc = DocumentHelper.parseText(str);
			root = doc.getRootElement();
			String msgType = root.getName();
			if(msgType.equals("CLR"))
			{
				String attrMID = SCSPUtils.parseField(root, "MID", true);
				
				System.out.print(attrMID.toString());
			}
		   	Element msg =DocumentHelper.createElement("DATA");
		   	
		   	Element msg1 =DocumentHelper.createElement("root1");
		   	SCSPUtils.addElement(msg1, "t1", "tt1");
		   	SCSPUtils.addElement(msg1, "t2", "tt2");
		   	SCSPUtils.addElement(msg1, "t3", "tt3");
		   	msg.setText(str);
			root.add(msg);
		   	System.out.println(root.asXML());
		   	System.out.println(SCSPUtils.writeXml(root));
		   	System.out.println(msg1.elementText("t2"));
		   	System.out.println(msg1.elementText("t3"));
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FieldNotExistException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//HashMap的遍历与删除
		ConcurrentHashMap<String,String> aMap = new ConcurrentHashMap<String,String>();
		aMap.put("1", "1");
		aMap.put("2", "1");
		aMap.put("3", "1");
		aMap.put("4", "1");
		System.out.println(aMap);
		for(String a:aMap.keySet())
		{
			if(a.compareTo("2")<=0)
			{
				aMap.remove(a);
			}
		}
		System.out.println(aMap);
		ConcurrentHashMap<String,String> b = aMap;
		aMap = new ConcurrentHashMap<String,String>();
		aMap.put("4", "4");
		aMap.put("5", "5");
		System.out.println(b);
		System.out.println(aMap);
		//
		String[] ret = null;
		   String hostName;
		try {
			hostName = InetAddress.getLocalHost().getHostName();

		   if(hostName.length()>0){
		    InetAddress[] addrs = InetAddress.getAllByName(hostName);
		    if(addrs.length>0){
		     ret = new String[addrs.length];
		     for(int i=0 ; i< addrs.length ; i++){
				System.out.println(addrs[i].getHostAddress());
		     }
		    }
		   }
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    }
    
	/**
	 * Make session id 
	 *
	 * @param host host id
	 * @return session id
	 */
	static public String makeSessionID(String host)
	{
		return host + ";" + _sessionIdHigh + ";" + (_sessionIdLow++);

	}

	private static final int _sessionIdHigh = (int) (System.currentTimeMillis() / 1000L);
	private static int _sessionIdLow = 0;

	public static void sleep(long ms)
	{
		try
		{
			Thread.sleep(ms);
		}
		catch (InterruptedException e)
		{
		}
	}
	public static String formatMessage(SCSPMessage msg) throws Exception
	{
	   	StringBuilder sb = new StringBuilder();
	   	Element root;
	   	if(!msg.isParsed())
	   	{
	   		root = Comutils.parseText(msg.getBodyStr()).getRootElement();
	   		msg.setElement(root);
	   	}
	   	else
	   	{
	   		root  = msg.getElement();
	   	}
	   	int length = msg.getLength();
	   	if(length == 0)
	   	{
	   		msg.serialize();
	   		length = msg.getLength();
	   	}
	   	sb.append("\n==================== Type:").append(root.getName()).append(", Size:").append(length).append("====================\n");
	   	sb.append(writeXml(root));
	   	sb.append("\n=====================================================\n");
	   	return sb.toString();
	}
	private static String formatElement(Element doc)
	{
	   	StringBuilder sb = new StringBuilder();
		for(Object o: doc.attributes())
		{
			Attribute a  = (Attribute) o;
			sb.append(a.getName()).append(" = ");
			Element dataRoot = null;
			if(a.getName().equals("DATA"))
			{
				String value = a.getValue();
				if(value.trim().length()> 0)
				{
					try {
						dataRoot = DocumentHelper.parseText(value).getRootElement();
					} catch (DocumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}
			if(dataRoot != null)
			{
				sb.append(writeXml(dataRoot)).append('\n');
			}
			else
			{
				sb.append(a.getValue()).append('\n');
			}			
		}
	   	return sb.toString();
	}
	public static String writeXml(Element doc)
    {
		XMLWriter writer = null;
       try {
           
           OutputFormat format = OutputFormat.createPrettyPrint();
           format.setEncoding("UTF-8");
           //注释：创建输出(目标)
           StringWriter out=new StringWriter();
           ///注释：创建输出流
           writer = new XMLWriter(out,format);
           //注释：输出格式化的串到目标中，执行后。格式化后的串保存在out中。
           writer.write(doc);
           //注释：返回我们格式化后的结果
           return out.toString();   
       } catch (Exception e) {

       }
       finally
       {
           if (writer!=null)
           {
              try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
           }
       }
       return null;
    }
	public static void addElement(Element rootSCA, String eleTag,
			String eleValue) {
		if(eleValue == null)
			return;
		Element ele = rootSCA.addElement(eleTag);
		ele.setText(eleValue);
	}
	
	public static void addElement(Element rootSCA, String eleTag,
			Element eleValue) {
		if(eleValue == null)
			return;
		Element ele = rootSCA.addElement(eleTag);
		ele.add(eleValue);
	}
}
